package thread.interrupt;

import java.io.IOException;
import java.net.ServerSocket;
/*
Aim:
验证1:Java1.0之前就存在的传统的I/O,在阻塞状态下，无法响应中断请求，导致线程无法退出阻塞状态。
比如ServerSocket的accept方法根本不抛出异常。
很幸运，Java平台为这种情形提供了一项解决方案，即调用阻塞该线程的套接字的close()方法。
在这种情形下，如果线程被I/O操作阻塞，当调用该套接字的close方法时，
该线程在调用accept地方法将接收到一个SocketException（SocketException为IOException的子异常）异常，
这与使用interrupt()方法引起一个InterruptedException异常被抛出非常相似，从而实现 阻塞线程进入异常代码块中。
*/
class IoInterrupt extends Thread {
    volatile ServerSocket socket;

    public static void main(String args[]) throws Exception {
        IoInterrupt thread = new IoInterrupt();
        System.out.println("Starting thread...");
        thread.start();
        Thread.sleep(3000);
        System.out.println("Asking thread to stop by interrupt.");
        Thread.currentThread().interrupt();// 再调用interrupt方法
        Thread.sleep(5000);
        System.out.println("Thread doesn't stop after interrupted.");
        System.out.println("Asking thread to stop by closing socket.");
        thread.socket.close();// 再调用close方法
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
        }
        System.out.println("Stopping application...");
    }

    public void run() {
        try {
            socket = new ServerSocket(8888);
        } catch (IOException e) {
            System.out.println("Could not create the socket...");
            return;
        }
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("Waiting for connection...");
            try {
                socket.accept();
            } catch (IOException e) {
                System.out.println("accept() failed or interrupted...");
                System.out.println("In catch block, isInterrupted:  " + Thread.currentThread().isInterrupted());
                Thread.currentThread().interrupt();//重新设置中断标示位
            }
        }
        System.out.println("Thread exiting under request...");
    }
}